package com.region.loadbalancer.monitor.stat;

import com.region.loadbalancer.group.Server;

import javax.net.ssl.*;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * https protocol detection service
 *
 * @author liujieyu
 * @date 2023/5/26 15:40
 * @desciption
 */
public class HttpsDetectionConnection implements DetectionConnection {

    /**
     * The default timeout is 100 milliseconds
     */
    private int timeout = 100;

    public HttpsDetectionConnection() {
        this(100);
    }

    public HttpsDetectionConnection(int timeout) {
        this.timeout = timeout;
    }

    @Override
    public boolean connect(Server server) {
        try {
            URL url = new URL(server.getServerAllInfo());
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(this.timeout);
            urlConnection.setSSLSocketFactory(getSSLSocketFactory());
            urlConnection.setHostnameVerifier((s, sslSession) -> true);
            int responseCode = urlConnection.getResponseCode();
            if (responseCode < 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    private SSLSocketFactory getSSLSocketFactory() throws Exception {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, new SecureRandom());
        return ctx.getSocketFactory();
    }
}
